package org.belkodevelop.geocoding.adress.json.parser;

import java.util.*;
import org.belkodevelop.geocoding.adress.domen.CompositeAdress;
import org.belkodevelop.geocoding.adress.json.AdressComponent;
import org.belkodevelop.geocoding.adress.json.GoogleAdress;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoogleAdressConverter {
    
    private static Mapper mapper;
    
    @Autowired
    public void setMapper(Mapper mapper) {
        this.mapper = mapper;
    }
    
    private GoogleAdressConverter() {   
    }
    
    private final static List<String> needTypes = Arrays.asList(
        "room",
        "floor",
        "street_number",
        "street_address",
        "route",
        "sublocality",
        "locality",
        "administrative_area_level_3",
        "administrative_area_level_2",
        "administrative_area_level_1",
        "country"
    );
    
    private static Map<String, String> findValuesComponent(GoogleAdress googleAdress) {
        Map<String, String> result = new HashMap<>();
        for (AdressComponent ac: googleAdress.getAddressComponents()) {
            for (String type: needTypes) {
                if (ac.getTypes().contains(type)) {
                    result.put(type, ac.getShortName());
                }
            }
                    
        }
        return result;
    }
    
    static public CompositeAdress getCompositeAdress(GoogleAdress googleAdress) {
        Map<String, String> mapValues = findValuesComponent(googleAdress);
        CompositeAdress compositeAdress = mapper.map(mapValues, CompositeAdress.class);
        return compositeAdress;
    }
    
}
